import React, { useState } from 'react'
import { Button, Modal, Form, Input } from 'antd';
import { useAuth } from '../../context/AuthProvider';
import { postDraft } from '../../api/draft';

const UploadButton = ({draft,setDraft}) => {
    const { user } = useAuth();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onFinish = (values) => {
        postDraft({ ...values, draftUser: user.userId })
            .then(res => {
                console.log(res);
                setDraft({
                    ...draft,
                    content:[{...res.data,user:user},...draft.content],
                    totalElements: draft.totalElements+1
                })
                setIsModalOpen(false);
            })
    }

    return (
        <div style={{ textAlign: "right" }}>
            <Button onClick={showModal} type="primary">
                新增投稿
            </Button>
            <Modal
                title="新增投稿"
                open={isModalOpen}
                onCancel={handleCancel}
                footer={null}
            >
                <Form
                    name="basic"
                    layout='vertical'
                    style={{
                        maxWidth: 400,
                        margin: '50px auto'
                    }}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item
                        label="投稿标题"
                        name="draftTitle"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your username!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="投稿内容"
                        name="draftContext"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            block
                            shape='round'
                            type="primary"
                            htmlType="submit"
                        >
                            新增投稿
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default UploadButton